package com.xf.tourismapp.fragments;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.xf.tourismapp.R;
import com.xf.tourismapp.services.MusicService;

import java.text.SimpleDateFormat;
import java.util.Locale;

public class MusicFragment extends Fragment implements View.OnClickListener {
    private ImageView albumCover;
    private TextView musicTime;
    private SeekBar musicSeekBar;
    private TextView musicTotal;
    private Button btnPlayOrPause;

    private Intent intent;  //绑定和解绑定Service的意图对象
    private MusicService musicService;  //音乐播放Service对象
    private final ServiceConnection conn = new MyConnection();  //Actvity与Service绑定时的连接通道
    private ObjectAnimator animator;  //旋转动画对象
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss", Locale.CHINA);  //时间格式 分分：秒秒
    private boolean tag = false;//旋转图像动画播放状态标志位，true为旋转状态，false为停止状态
    private Activity activity;
    private boolean mIsBound;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_music, container, false);
        initView(v);
        initAnimation();  //初始化旋转动画
        return v;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = (Activity) context;
        bindMusicService();  //绑定Service方法
        mIsBound = true;
    }

    private void unBindMusicService() {
        if (mIsBound) {
            activity.unbindService(conn);
            mIsBound = false;
        }
    }

    //设置属性动画
    private void initAnimation() {
        animator = ObjectAnimator.ofFloat(albumCover, "rotation", 0.0f, 360.0f);
        animator.setInterpolator(new LinearInterpolator()); //设置旋转速度为线性匀速
        animator.setDuration(10000);   //设置一次动画旋转的时长  单位 ms 毫秒
        animator.setRepeatCount(-1);  //设置动画重复循环的次数 ，一直循环
    }

    @Override
    public void onDetach() {
        super.onDetach();
        unBindMusicService();//解绑Service
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unBindMusicService();
        Intent i = new Intent(activity, MusicService.class);
        activity.stopService(i);//停止Service
    }

    private void bindMusicService() {
        intent = new Intent(activity, MusicService.class);
        activity.startService(intent);  //先启动
        activity.bindService(intent, conn, Context.BIND_AUTO_CREATE);   //后绑定
    }

    //Activity与Service绑定时的通道
    private class MyConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MusicService.MyBinder myBinder = (MusicService.MyBinder) iBinder;
            musicService = myBinder.getService();//获取MusicService对象
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            musicService = null;
        }
    }

    private void initView(View v) {
        albumCover = v.findViewById(R.id.albumCover);
        musicTime = v.findViewById(R.id.musicTime);
        musicSeekBar = v.findViewById(R.id.MusicSeekBar);
        musicTotal = v.findViewById(R.id.musicTotal);
        btnPlayOrPause = v.findViewById(R.id.btnPlayOrPause);
        Button btnStop = v.findViewById(R.id.btnStop);
        Button btnQuit = v.findViewById(R.id.btnQuit);

        btnPlayOrPause.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnQuit.setOnClickListener(this);
        musicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int pos, boolean fromUser) {
                if (fromUser) {//通知音乐播放器改变播放进度
                    musicService.seekTo(pos);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btnPlayOrPause) {
            if (musicService != null) {
                if (!musicService.isPlaying()) {
                    // 1.ImageView播放旋转动画
                    if (!tag) {//tag记录当前播放状态false为暂停状态 true为播放状态
                        animator.start();
                        tag = true;
                    } else {
                        animator.resume();  //从暂停状态继续播放动画
                    }
                    //2.调用MusicService对象播放音乐
                    musicService.playOrPause();
                    //3.获取音乐信息并更新界面
                    btnPlayOrPause.setText(R.string.fragment_music_text_zhanting);
                    int total = musicService.getDuration(); //mp3总时长
                    mHandler.postDelayed(runnable, 100);//每0.1秒更新当前播放进度
                    musicTotal.setText(simpleDateFormat.format(total));   //mp3总时长
                    musicSeekBar.setMax(total);  //设置进度条最大进度 ==音乐总时长

                } else {
                    animator.pause();  //暂停动画
                    btnPlayOrPause.setText(R.string.fragment_music_text_bofang);
                    if (musicService == null) {
                        bindMusicService();
                    }
                    musicService.playOrPause();  //暂停
                }
            }
        } else if (id == R.id.btnStop) {
            if (musicService != null) {
                musicService.stop();//停止音乐
            }
            animator.end();//结束动画
            mHandler.removeCallbacks(runnable); //停止界面更新任务
            tag = false;
            musicSeekBar.setProgress(0);   //设置当前进度清零
            musicTime.setText(R.string.fragment_music_text_shichang);  //mp3当前播放进度清零
            btnPlayOrPause.setText(R.string.fragment_music_text_bofang);
        } else {
            //解绑定服务
            unBindMusicService();
            activity.stopService(intent);//停止服务
            mHandler.removeCallbacks(runnable); //停止界面更新任务
            activity.finish(); //关闭当前界面
        }
    }

    //定义一个Handler对象循环更新当前播放进度
    public Handler mHandler = new Handler();
    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (musicService != null) {
                if (musicService.isPlaying()) {   //更新任务
                    int current = musicService.getCurrentPosition(); //mp3当前播放进度
                    musicTime.setText(simpleDateFormat.format(current));  //mp3当前播放进度
                    //进度条进度更新
                    musicSeekBar.setProgress(current);   //设置当前进度
                    mHandler.postDelayed(this, 100);   //递归实现循环
                } else {
                    btnPlayOrPause.setText(R.string.fragment_music_text_bofang);
                }
            }
        }
    };
}